<template>
  <div>
    <!-- 搜索 -->
    <div class="search">
      <a-form style="padding-top: 20px" :model="form" :hideRequiredMark="true" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row>
          <a-col :span="6" :lg="6" :xs="9" :md="8">
            <a-form-item>
              <a-range-picker
                v-model:value="time"
                style="width: 100%"
                :ranges="ranges"
                show-time
                format="YYYY/MM/DD HH:mm:ss"
                @change="panelChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="4" :offset="1" :lg="4" :xs="7" :md="7">
            <a-form-item name="keyword" label="">
              <a-input v-model:value="form.keyword" placeholder="请输入搜索内容"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="2" :offset="1"><a-button type="primary" @click="search" class="d-a-center">搜索</a-button></a-col>
        </a-row>
      </a-form>
    </div>
    <div class="">
      <div
        class="d-j-bet d-a-center"
        v-for="(item, index) in list"
        :key="index"
        style="height: 106px; border: 0.1px solid #e5e5e5; padding: 0 1% 0 2%"
      >
        <div class="d-a-center" style="width: 100%; height: 73px">
          <div class="df ava-img" style="">
            <img :src="item.avatarJson" class="ava-img" alt="" />
          </div>
          <div class="d-c-center reply-ll" style="" v-if="item.unreadCount > 0">
            {{ item.unreadCount }}
          </div>
          <div
            class="box d-j-bet d-a-center"
            style="width: 95%; height: 100%"
            :style="item.unreadCount == 0 ? 'padding: 0 1% 0 2%;' : 'padding: 0 1% 0 1%;'"
          >
            <div class="" style="width: 80%">
              <div class="user-nick">{{ item.userNickname }}</div>
              <div class="user-time">{{ item.lastMessageTime }}</div>
              <div class="user-msg omittwo" style="">
                <div class="" style="" v-if="item.messageType == 0">{{ item.lastMessage }}</div>
                <div class=" " v-if="item.messageType == 1">[服务详情]</div>
                <div class=" " v-if="item.messageType == 2">[图片]</div>
              </div>
            </div>

            <div style="" class="d-a-center">
              <div class="d-c-center reply-numl" style="" @click="openReplyAmodal(item, 0, index)">回复消息</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="d-j-end d-a-center">
      <a-pagination
        v-model:current="pageNum"
        v-model:page-size="pageSize"
        :total="listTotal"
        @change="onChange"
        :show-total="listTotal => `共 ${listTotal} 条`"
      />
    </div>
    <!-- 回复消息弹窗 -->
    <a-modal width="1200px" :bodyStyle="{ background: '#f3f3f3' }" v-model:visible="replyVisible" title="" @ok="handleOk" :footer="null">
      <div style="width: 100%; height: 100%; height: 700px" class="df">
        <!-- 下拉刷新 -->
        <div class="modal-left wh-ten" style="">
          <div ref="listContainer" class="test-box" style="height: 100%" @scroll="listScroll">
            <!-- <pre></pre> -->
            <div
              class="d-a-center box"
              v-for="(item, index) in list"
              :key="index"
              :style="active == item.chatId ? 'background: #dedede;' : ''"
              style="border: 0.5px solid #e5e5e5; padding: 0 2% 0 2%; height: 106px"
              @click="openReplyAmodal(item, 1, index)"
            >
              <div class=" " style="">
                <img :src="item.avatarJson" alt="" class="ava-img" style="" />
              </div>
              <div class="box d-c-center reply-lll" style="margin-top: -70px; margin-left: -10px" v-if="item.unreadCount">
                {{ item.unreadCount }}
              </div>

              <div class="box" :style="item.unreadCount == 0 ? 'padding: 0 1% 0 5%;width:75%' : 'padding: 0 1% 0 1%;width:74.5%'">
                <div style="width: 60%" class="omit user-nick">
                  {{ item.userNickname }}
                </div>
                <div class="user-time" style="">
                  {{ item.lastMessageTime }}
                </div>
                <div class="user-msg">
                  <div class="omit" style="width: 270px" v-if="item.messageType == 0">
                    {{ item.lastMessage }}
                  </div>
                  <div class=" " v-if="item.messageType == 1">[服务详情]</div>
                  <div class=" " v-if="item.messageType == 2">[图片]</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-right wh-ten" style="height: 100%">
          <div class="text-center" style="font-weight: 400; font-size: 16px; color: #000000">
            {{ nickname }}
          </div>
          <div class="text-center" style="font-weight: 400; font-size: 14px; color: #979797">用户ID：{{ chatHistoryInfo.userId }}</div>
          <!-- 发送和收到的消息模板  -->
          <div @scroll="handleScroll" class="test-box bottom-box msg-list" style="background: #f3f3f3">
            <div style="height: 40px; background: #f3f3f3" class="" ref="scrollContainer"></div>

            <div
              class=""
              style="padding: 0.5% 2%"
              v-for="(item, index) in chatHistory"
              :key="index"
              :style="item.roleType != 0 ? 'd-j-end' : ''"
            >
              <div class="text-center box" v-if="shouldDisplayTime(item.createdAt, index)" style="padding-bottom: 1%; color: grey">
                {{ item.createdAt }}
              </div>
              <div class="df" :class="item.roleType != 0 ? '' : 'd-j-end'" style="width: 100%">
                <div v-if="item.roleType == 1 || item.roleType == 2">
                  <img :src="userAvater" class="chat-ava yuan" alt="" />
                </div>
                <div class="d-a-center" :style="item.roleType != 0 ? 'margin-left:2%' : 'margin-right:1%;'">
                  <div
                    class="box"
                    v-if="item.messageType == 0"
                    :style="item.roleType != 0 ? 'background: #FFFFFF;' : 'background: rgba(31,147,134,0.1);'"
                    style="padding: 8px 12px 8px 12px; border-radius: 17px; font-weight: 400; font-size: 14px; color: rgba(0, 0, 0, 0.9)"
                  >
                    {{ item.message }}
                  </div>

                  <div class="box box-detail d-a-center df" style="" v-if="item.messageType == 1">
                    <div class="" style="margin-right: 3%" v-if="item.roleType != 2">
                      <img :src="item.message.coverJson" alt="" class="ava-img" />
                    </div>
                    <div class="" style="width: 100%">
                      <div class="d-j-bet">
                        <div style="width: 70%" class="omit user-nick">
                          {{ item.message.serviceName }}
                        </div>
                        <div class="user-time">{{ getOrderListStatus(item.message.status) }}</div>
                      </div>
                      <div v-if="item.roleType == 2">
                        <div class="user-nick omit">用户姓名：{{ item.message.name }}；服务地址：{{ item.message.address }}</div>
                      </div>
                      <div class="omit user-time">{{ item.message.scheduleTime }}</div>

                      <div class="d-j-bet d-a-center">
                        <div class="red-pri">¥{{ item.message.price }}*{{ item.message.num }}</div>
                        <div class="d-c-center action-btn" style="" @click="getOrder(item.message.number)">查看订单</div>
                      </div>
                    </div>
                  </div>
                  <div v-if="item.messageType == 2" style="width: 130px">
                    <img :src="item.message" @click="previewImage(item.message)" alt="" style="max-width: 100%; height: auto" />
                  </div>
                </div>
                <div v-if="item.roleType == 0">
                  <img src="http://loto.oss-cn-shanghai.aliyuncs.com/email/b8ad69f2e0854d21.png" style="" class="chat-ava yuan" alt="" />
                </div>
              </div>
            </div>
          </div>
          <!-- 输入框 -->
          <div class="mar input-box" style="width: 100%; padding-bottom: 1%">
            <div class="">
              <div class="d-j-around" style="width: 100px; margin: 10px">
                <img
                  src="http://loto.oss-cn-shanghai.aliyuncs.com/email/8169fa70ce4f4023.png"
                  style="width: 30px; height: 30px"
                  alt=""
                  @click="openCommonPhrases()"
                />
                <a-upload
                  :custom-request="uploadFile"
                  :before-upload="beforeUpload"
                  :showUploadList="false"
                  @change="handleChange"
                  class=""
                  accept=".jpg,.png,.jpeg"
                  :max-count="1"
                >
                  <img src="http://loto.oss-cn-shanghai.aliyuncs.com/email/67b5b951921c4c71.png" style="width: 30px; height: 30px" alt="" />
                </a-upload>
              </div>
            </div>
            <a-textarea
              v-model:value="message"
              show-count
              placeholder="请输入内容"
              :rows="7"
              :showCount="false"
              :auto-size="{ minRows: 9, maxRows: 9 }"
              :bordered="false"
              @pressEnter="toSendMessage(0)"
            />
            <div class="d-j-end">
              <!-- 点击发送只能发送文字，图片选择是单独的 -->
              <!-- <div class="action-btn d-c-center" @click="toSendMessage(0)" style="width: 80px; padding: 0.5%; margin-top: 1%">发送</div> -->
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    <a-modal
      width="960px"
      wrapClassName="modal-style"
      v-model:visible="commonVisible"
      title=""
      @ok="handleOk"
      :footer="null"
      @cancel="commonCancel"
    >
      <div style="margin-bottom: 1%" class="">
        <div
          class="d-j-bet"
          v-for="(item, index) in commonPhrasesList"
          :key="index"
          style="padding: 1%; border-bottom: 1px solid lightgrey; width: 100%"
        >
          <div class="" v-if="phraseId != item.id">{{ item.phrase }}</div>
          <div v-if="phraseId == item.id">
            <a-textarea v-model:value="item.phrase" allowClear="true" :rows="2" />
            <a-button type="link" size="middle" @click="addCommonPhrase(item.phrase)">保存</a-button>
          </div>
          <div style="width: 40%" class="d-j-end d-a-center">
            <a-button
              type="link"
              size="middle"
              v-for="(i, indexl) in phraseAction"
              :key="indexl"
              @click="editPhrase(indexl, item.id, item.phrase)"
              >{{ i }}</a-button
            >
          </div>
        </div>
        <a-button style="margin: 1%" type="primary" @click="addCommonPhraseStatus(1)">添加常用语...</a-button>
        <div v-show="isAddPhrase">
          <a-textarea v-model:value="phrase" placeholder="请输入常用语..." allowClear="true" :rows="2" />
          <a-button type="link" size="middle" @click="addCommonPhrase(phrase)">保存</a-button>
        </div>
        <div class="d-j-end d-a-center">
          <a-pagination
            v-model:current="phraseInfo.pageNum"
            v-model:page-size="phraseInfo.pageSize"
            :total="phraseListTotal"
            @change="onPhraseChange"
            :show-total="phraseListTotal => `共 ${phraseListTotal} 条`"
          />
        </div>
      </div>
    </a-modal>
    <a-modal width="40%" v-model:visible="preImageStatus" title="" :footer="null">
      <div class="d-c-center"><img :src="preImage" alt="" style="width: 300px; height: 600px" /></div>
    </a-modal>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs, onMounted, nextTick } from 'vue'
import UploadFile from '@/components/common/UploadFile.vue'
import { Modal, notification, message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import router from '@/router/index.js'
import { uploadPicture } from '@/api/email/index.js'
import { wsURL } from '@/utils/options.js'
// import {
// 	deleteObjBlank
// } from "@/assets/js/common.js";
import {
  getMessagesList,
  getAllCommonPhrases,
  getChatHistory,
  sendMessage,
  markMessagesAsRead,
  createCommonPhrase,
  deleteCommonPhrase,
  updateCommonPhrase
} from '@/api/chat/index'
import { useStore } from 'vuex'
export default {
  components: {},
  setup() {
    // 有权限那这个人就拥有客服功能
    const store = useStore()
    let map = {
      18888888888: '80',
      16666666666: '81'
    }
    let map1 = {
      18888888888: '/2',
      16666666666: '/1'
    }
    let serviceId = map[store.state.account]

    const chatHistoryInfo = reactive({
      chatId: '',
      message: '',
      messageType: 0,
      questionTemplatesId: '',
      receiverId: '',
      roleType: 0,
      senderId: serviceId,
      sessionType: ''
    })
    const scrollContainer = ref(null)
    const listContainer = ref(null)
    const getOrderListStatus = status => {
      let title = ''
      switch (status) {
        case 1:
          title = '待付款'
          break
        case 2:
          title = '待抢单'
          break
        case 3:
          title = '待服务'
          break
        case 4:
          title = '服务中' //服务中
          break
        case 5:
          title = '已完成'
          break
        case 6:
          title = '已取消'
          break
        case 7:
          title = '已退款'
          break
        case 8:
          title = '异常单'
          break
        case 9:
          title = '退款中' //退款中
          break
        case 10:
          title = '已拒绝' //已拒绝
          break
        default:
          break
      }
      return title
    }
    const form = reactive({
      beginTime: '',
      endTime: '',
      nick: '',
      keyword: ''
    })
    const data = reactive({
      userAvater: '',
      editValue: false,
      phraseId: '',
      msgLoding: false,
      isEditStatus: 0,
      isAddPhrase: false,
      phrase: '',
      phraseAction: ['发送', '编辑', '删除'],
      active: 0,
      listTotal: 0,
      phraseListTotal: 0,
      fileList: [],
      chatHistory: [],
      nickname: '',
      message: '',
      loading: true,
      time: [],
      id: '',
      visible: false,
      replyVisible: false,
      commonPhrasesList: [],
      list: [],
      handleList: [],
      lastId: 0,
      proLen: 0,
      lastValue: 0,
      commonVisible: false,
      preImageStatus: false,
      preImage: '',
      isSend: false,
      phraseInfo: {
        pageNum: 1,
        pageSize: 10
      }
    })
    const commonCancel = () => {
      console.log(11111111)
      data.phraseId = ''
      data.isEditStatus = 0
      data.isAddPhrase = false
    }

    function previewImage(image) {
      data.preImage = ''
      data.preImage = image
      data.preImageStatus = true
    }
    async function editPhrase(indexl, id, phrase) {
      if (indexl == 0) {
        toSendMessage(0, phrase)
        message.success('发送成功！')
      } else if (indexl == 1) {
        // 编辑0,新增1
        data.editValue = true
        data.isEditStatus = 0
        // addCommonPhraseStatus(0)
        data.phraseId = id
        data.phrase = phrase
      } else if (indexl == 2) {
        // 删除
        let res = await deleteCommonPhrase(id)
        if (res.success) {
          message.success('删除成功！')
        }
        getAllCommonPhrasesInit()
      }
    }
    async function addCommonPhraseStatus(value) {
      if (value == 1) {
        data.phrase = ''
      }
      data.isEditStatus = value
      data.isAddPhrase = !data.isAddPhrase
    }
    const beforeUpload = file => {
      const isType = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
      if (!isType) {
        message.error('文件格式错误，仅允许.jpg,.jpeg,.png格式图片!')
      }
      return isType
    }
    // 选择时间
    const panelChange = (date, dateString) => {
      form.beginTime = dateString[0]
      form.endTime = dateString[1]
    }
    const openCommonPhrases = () => {
      data.commonVisible = true
      getAllCommonPhrasesInit()
    }
    const uploadFile = async file => {
      let formData = new FormData()
      formData.append('file', file.file)
      let res = await uploadPicture(formData, 'email')
      if (res.success) {
        chatHistoryInfo.message = res.object
        toSendMessage(2)
      }
    }
    // 查询
    const search = () => {
      if (Object.keys(form).length == 0) {
        message.warning('请输入你要搜索的内容！！！')
        return
      }
      // deleteObjBlank(form);
      pageNum.value = 1
      init()
    }

    const openReplyAmodal = async (item, value, index) => {
      data.isSend = true
      data.active = item.chatId
      data.userAvater = item.avatarJson
      data.lastId = 0
      data.chatHistory = []
      if (item.unreadCount > 0) {
        let resl = await markMessagesAsRead(item.chatId, item.receiverId)
        if (resl.success) {
          console.log('消息已读成功')
          nextTick(() => {
            init()
          })
        }
      }
      if (item.receiverId == serviceId) {
        chatHistoryInfo.userId = item.senderId
      } else {
        chatHistoryInfo.userId = item.receiverId
      }
      // 这里只可能为1用户或者2护士
      chatHistoryInfo.sessionType = item.sessionType

      data.nickname = item.userNickname
      data.replyVisible = true
      getChatInfo(item.chatId)
    }
    const handleChange = file => {
      file.fileList.forEach(f => {
        f.status = 'done'
      })
    }

    const shouldDisplayTime = (prevTimeStr, index) => {
      if (data.chatHistory.length < 2 || index < 1 || data.chatHistory.length - index <= 1) return prevTimeStr ? true : false

      let currentTimeStr
      // 将时间字符串转换为Date对象
      const prevTime = new Date(prevTimeStr)
      const currentTime = new Date(data.chatHistory[index + 1].updatedAt)

      // 计算时间差（毫秒）
      const diff = currentTime - prevTime

      return diff <= -60000
    }
    const handleOk = e => {
      data.visible = false
    }
    const pageNum = ref(1)
    const pageSize = ref(10)
    const onChange = num => {
      pageNum.value = num
      init()
    }
    const onPhraseChange = num => {
      data.phraseInfo.pageNum = num
      getAllCommonPhrasesInit()
      console.log(222, num, data.phraseInfo.pageNum)
    }
    init()
    initWebSocket()

    async function toSendMessage(messageType, message) {
      // console.log('发送消息--------,sessiontype,1是与护士，2是与用户');
      data.isSend = true
      // roletype 1是用户，2是护士，0是客服
      if (!chatHistoryInfo.message) {
        chatHistoryInfo.message = data.message
      }
      if (message) {
        chatHistoryInfo.message = message
      }
      chatHistoryInfo.messageType = messageType
      chatHistoryInfo.receiverId = chatHistoryInfo.userId
      if (data.message || chatHistoryInfo.message) {
        let res = await sendMessage(chatHistoryInfo)
        // 成功之后push,客服只能发文字或者图片0和2
        if (res.success) {
          data.chatHistory.unshift(JSON.parse(JSON.stringify(chatHistoryInfo)))
          data.message = ''
          chatHistoryInfo.message = ''
          if (message) {
            data.commonVisible = false
            data.isAddPhrase = false
          }
          scrollToBottom()
          init()
          // data.active = 0
        }
      }
    }
    async function getOrder(number) {
      router.push({
        path: '/order/center/order-detail',
        query: {
          number: number
        }
      })
    }

    async function addCommonPhrase(phrase) {
      if (phrase) {
        if (data.isEditStatus == 1) {
          let res = await createCommonPhrase({
            phrase: phrase,
            adminId: serviceId
          })
          if (res.object.success) {
            message.success('新增成功！')
          } else {
            message.error(res.object.object)
          }
        } else if (data.isEditStatus == 0) {
          // 编辑
          let commonPhrases = {
            phrase: phrase,
            adminId: serviceId
          }
          // console.log('llll', commonPhrases);
          let resl = await updateCommonPhrase(data.phraseId, commonPhrases)
          if (resl.success) {
            message.success('编辑成功！')
            data.phraseId = ''
          } else {
            message.error('已存在相同的常用短语！')
          }
        }
        data.isAddPhrase = false
        getAllCommonPhrasesInit()
      } else {
        message.error('请输入常用语！')
      }
    }
    // 收到的消息列表
    async function init() {
      initWebSocket()
      console.log('触发连接')
      data.loading = true
      let obj = {
        customerId: serviceId,
        startCreatedAt: form.beginTime,
        endCreatedAt: form.endTime,
        nick: form.keyword,
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
      // console.log(333, obj);
      let res = await getMessagesList(obj.customerId, obj.startCreatedAt, obj.endCreatedAt, obj.nick, obj.pageNum, obj.pageSize)
      if (res.success) {
        let list = res.object.list
        console.log('初始化---', list)
        // res.object.list.forEach(i => {
        // 	i.userAvatar = i.avatarJson
        // })
        if (!data.replyVisible) {
          data.list = list
        } else {
          // 在发送就不push，不在发送为false就push
          // false不在发送
          if (list.length > 0) {
            if (!data.isSend) {
              data.list.push(...list)
            } else {
              data.list = list
            }
          } else {
            pageNum.value = 1
          }
        }
        data.listTotal = res.object.total
        data.loading = false
      }
      console.log(991111199, data.list)
    }

    function initWebSocket() {
      const _this = this
      var websocket = null
      if ('WebSocket' in window) {
        //这里写链接接口urlchatHistoryInfo.userId

        if (map[store.state.account]) {
          let port = map[store.state.account]
          let port1 = map1[store.state.account]
          websocket = new WebSocket(wsURL + port + port1)
          console.log('链接中')
        } else {
          message.info('请使用客服账号登录')
        }
      } else {
        alert('该浏览器不支持websockt！')
      }
      websocket.onopen = function (event) {
        console.log('建立连接', event)
        // websocket.send('Hello WebSockets!');
      }
      websocket.onclose = function (event) {
        console.log('连接关闭')
        _this.reconnect() //尝试重连websocket
      }
      websocket.onmessage = function (event) {
        let msg = JSON.parse(event.data)
        console.log('收到的消息-------', msg)
        let msgInfo = JSON.parse(msg.message)
        msgInfo.userAvatar = msg.avatarJson

        let index = ''
        data.list.forEach((i, idx) => {
          if (msg.chatId == i.chatId) {
            index = idx
          }
        })
        // console.log('1111d1ata.list', index, data.list);
        // data.list[index] = msg

        if (chatHistoryInfo.userId == msg.senderId || chatHistoryInfo.userId == msg.receiverId) {
          // console.log('聊天记录push', chatHistoryInfo.userId, msg.senderId);
          if (msgInfo.messageType == 1) {
            // console.log('msgInfo.messageType', msgInfo.messageType);
            msgInfo.message = JSON.parse(msgInfo.message)
          }
          data.chatHistory.unshift(msgInfo)
          scrollToBottom()
        }
        init()
        console.log('消息列表----', data.list)
        // console.log('服务器收到的消息', msg, msgInfo);
      }
      websocket.onerror = function () {
        console.log('websocket通信发生错误！')
        // ——this.initWebSocket()
      }
      window.onbeforeunload = function () {
        websocket.close()
      }
    }
    // 常用语列表
    async function getAllCommonPhrasesInit() {
      let rel = await getAllCommonPhrases(data.phraseInfo.pageNum, data.phraseInfo.pageSize)
      if (rel.success) {
        data.commonPhrasesList = rel.object.list
        data.phraseListTotal = rel.object.total
        console.log('data.commonPhrasesList', data.commonPhrasesList)
      }
    }
    // 聊天记录详情
    async function getChatInfo(id = '') {
      let res = await getChatHistory(data.lastId, 10, serviceId, chatHistoryInfo.userId)
      if (id && id !== data.active) {
        console.log('点快了 阻塞渲染')
        return
      }
      if (res.success) {
        res.object.forEach((i, index) => {
          if (i.messageType == 1) {
            i.message = JSON.parse(i.message)
          }
        })
        data.proLen = res.object.length
        let list = res.object.reverse()
        if (data.chatHistory.length > 0) {
          data.chatHistory = data.chatHistory.concat(list)
        } else {
          data.chatHistory = list
        }
        data.msgLoding = false
        // console.log('data.chatHistory----', data.chatHistory);
        // if (data.lastId == 0) {
        //   scrollToBottom()
        // }
      }
    }
    const listScroll = event => {
      console.log(3333, event)
      const { scrollTop, clientHeight, scrollHeight } = event.target
      // 当滚动到底部时加载更多
      if (scrollTop + clientHeight >= scrollHeight) {
        console.log('底部了')
        if (data.list.length < data.listTotal) {
          pageNum.value++
          init()
        }
      }
    }
    const handleScroll = event => {
      // console.log(event);
      const { scrollTop, clientHeight, scrollHeight } = event.target
      console.log('111', scrollTop - clientHeight + scrollHeight)
      if (scrollTop - clientHeight + scrollHeight >= 30) {
        // console.log('下滑');
      } else {
        // console.log('上滑');
        if (scrollTop <= 30) {
          // console.log('加载数据----------');
          if (data.msgLoding) return
          data.msgLoding = true
          // 上拉加载更多数据
          let len = data.chatHistory.length
          if (len >= 10 && data.proLen >= 10) {
            data.lastId = data.chatHistory[data.chatHistory.length - 1].id
            console.log('this.lastId', data.lastId)
            getChatInfo()
          } else {
            data.lastId = 0
          }
        }
      }
      data.lastValue = scrollTop
      // // 当滚动到底部时加载更多
      // if (scrollTop + clientHeight >= scrollHeight) {
      // 	// loadMoreMessages();
      // }
    }

    function scrollToBottom() {
      console.log('下滑-----------------')
      nextTick(() => {
        scrollContainer.value.scrollIntoView({
          behavior: 'smooth'
        })
      })
      // if (scrollContainer.value) {
      // 	console.log('scrollContainer.value', scrollContainer.scrollTop);
      // 	scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
      // }
    }
    onMounted(() => {
      // init()
      console.log('1111onmounted----------', scrollContainer.value)
      scrollToBottom()
    })
    // onUnmounted(() => {
    //   if (ws.value) {
    //     ws.value.close();
    //   }
    // });
    watch(data.chatHistory, async () => {
      console.log('watch---------------', scrollContainer.value)
      await nextTick()
      const topElement = scrollContainer.value
      if (topElement) {
        topElement.scrollTop = topElement.scrollHeight
      }
      // const listTopElement = listContainer.value;
      // if (listTopElement) {
      // 	listTopElement.scrollTop = listTopElement.scrollHeight;
      // }
    })

    return {
      commonCancel,
      previewImage,
      addCommonPhrase,
      addCommonPhraseStatus,
      editPhrase,
      getOrder,
      listScroll,
      pageNum,
      pageSize,
      onChange,
      onPhraseChange,
      handleScroll,
      scrollToBottom,
      ...toRefs(data),
      scrollContainer,
      listContainer,
      getChatInfo,
      form,
      search,
      panelChange,
      labelCol: {
        style: {
          fontWeight: 'bolder'
        }
      },
      chatHistoryInfo,
      handleOk,
      getOrderListStatus,
      openReplyAmodal,
      toSendMessage,
      openCommonPhrases,
      uploadFile,
      beforeUpload,
      handleChange,
      shouldDisplayTime
    }
  }
}
</script>
<style scoped lang="less">
.test-box {
  overflow-y: auto;
  border-right: 1px solid #e0e0e0;
}

.bottom-box {
  height: 390px;
}

.box-detail {
  width: 356px;
  height: 107px;
  background: #ffffff;
  border-radius: 17px;
  padding: 3%;
}

.user-nick {
  font-weight: 500;
  font-size: 14px;
  color: #333333;
}

.red-pri {
  font-weight: 400;
  font-size: 14px;
  color: #ec3b3b;
}

.user-time {
  font-weight: 400;
  font-size: 14px;
  color: #666666;
}

.user-msg {
  font-weight: 400;
  font-size: 14px;
  color: #999999;
}

.ava-img {
  width: 73px;
  height: 73px;
}

.chat-ava {
  width: 56px;
  height: 56px;
}

.reply-ll {
  border-radius: 50%;
  background-color: red;
  width: 23px;
  height: 20px;
  color: #fff;
  font-size: 12px;
  margin-left: -10px;
  margin-top: -70px;
}

.reply-lll {
  border-radius: 50%;
  background-color: red;
  width: 23px;
  height: 20px;
  color: #fff;
  font-size: 12px;
  // margin-left: -10px;
  margin-top: -80px;
}

.reply-num {
  border-radius: 50%;
  background-color: red;
  width: 30px;
  height: 25px;
  color: #fff;
  margin-left: -25px;
  margin-top: 3px;
}
.input-box {
  border-top: 1px solid #e0e0e0;
}
.reply-numl {
  border-radius: 4px;
  background-color: #2a9d8f;
  color: #fff;
  width: 118px;
  height: 37px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}

.search {
  background-color: #e6e6e6;
  padding-left: 20px;
  margin-bottom: 20px;
}

.modal-left {
  width: 35%;
  margin-top: 47px;
}

.modal-right {
  width: 65%;
}
.msg-list {
  display: flex;
  flex-direction: column-reverse;
}
.action-btn {
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
  width: 70px;
  height: 32px;
  background: #178175;
  border-radius: 4px;
}
::v-deep .ant-modal-body {
  background-color: red;
}
</style>
